package user.backing;

import java.util.Iterator;
import java.util.List;

import javax.faces.context.FacesContext;


import org.apache.myfaces.trinidad.component.core.data.CoreTable;
import org.apache.myfaces.trinidad.model.RowKeySet;

import core.constants.Constants.Constants;
import core.datasource.routing.ConnectionType;
import core.datasource.routing.CustomContextHolder;

import user.bo.UserBo;
import user.domain.User;


public class BackingUser {
 
	//DI via Spring
	UserBo userBo;
	
	User user;	
	private transient CoreTable table;
	private boolean readOnly;
	private String pageMode;
	
	
	public UserBo getUserBo() {
		return userBo;
	}
	public void setUserBo(UserBo userBo) {
		this.userBo = userBo;
	}
	
	/*
	 * 
	 * listUser
	 */
	public List<User> listUser(){
		return getUserBo().listUser();
	}
	
	// add or update user
	public String saveUser(){
		userBo.saveUser(getUser());		
		return "userSaved";
	}
	
	public String createForm() {
		user = new User();
		user.setName("");
		user.setCountry("");
		user.setGender("");
		user.setPassword("");
		return "createForm";
	}
	
	// go to view or update form
	public String getViewUpdateForm() {
		RowKeySet selectedKeySet = getTable().getSelectedRowKeys();
        Iterator iterator = selectedKeySet.iterator();
        while (iterator.hasNext()) {
        	int index = (Integer)iterator.next();
            setUser(getUserBo().listUser().get(index));
            break; //should only be one
        }
        
        if(pageMode.equals(Constants.Modes.VIEW)) {
        	readOnly = true;
        } else {
        	readOnly = false;
        }
		return "viewOrUpdateForm";
	}
	
	// delete selected user
	public String deleteSelected() {
		RowKeySet selectedKeySet = getTable().getSelectedRowKeys();
        Iterator iterator = selectedKeySet.iterator();
        while (iterator.hasNext()) {
        	int index = (Integer)iterator.next();
            setUser(getUserBo().listUser().get(index));
            break; //should only be one
        }
        userBo.deleteUser(getUser());
        return "userDeleted";
	}
	
	public String changeConnectionType() {
		if(CustomContextHolder.getConnectionType()==ConnectionType.GOLD){
			CustomContextHolder.setConnectionType(ConnectionType.MAIN);
		} else 
			CustomContextHolder.setConnectionType(ConnectionType.GOLD);
		return "connectionChanged";
	}
	
	
	public CoreTable getTable() {
		return table;
		
	}
	public void setTable(CoreTable table) {
		this.table = table;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}

	public boolean isReadOnly() {
		return readOnly;
	}

	public void setReadOnly(boolean readOnly) {
		this.readOnly = readOnly;
	}

	public String getPageMode() {
		return pageMode;
	}

	public void setPageMode(String pageMode) {
		this.pageMode = pageMode;
	}
	
	
}
